<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchemaAction } from './menu.data';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { BasicModal, useModalInner } from '/@/components/Modal';

  import {
    updateUsinghandledefAuthApi,
    addUsinghandledefAuthApi,
    UsinghandledefAuthInfoApi,
  } from '/@/api/admin/auth';

  export default defineComponent({
    name: 'ActionAuthModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let editData: any = {};

      const { createMessage } = useMessage();
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 90,
        baseColProps: { span: 24 },
        schemas: formSchemaAction,
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });

        isUpdate.value = data.isUpdate;
        updateSchema({
          field: 'handleCode',
          dynamicDisabled: unref(isUpdate),
        });
        if (unref(isUpdate)) {
          const ret = await UsinghandledefAuthInfoApi(data.record.id);

          editData = ret || {};
          setFieldsValue({
            ...ret,
          });
        } else {
          editData = {};
          editData.moduleId = data.moduleId;
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '添加操作' : '编辑操作'));

      async function handleSubmit() {
        try {
          const values = await validate();
          values.client = 0;
          if (!values.modelClassify) {
            values.modelId = null;
            values.modelClassify = null;
          }
          if (!unref(isUpdate)) {
            // 手动新增
            values.dataModelId = '-2';
          }

          setModalProps({ confirmLoading: true });
          // TODO custom api
          values.handleType = 0;
          const params = Object.assign(editData, values);
          const apiFn = unref(isUpdate) ? updateUsinghandledefAuthApi : addUsinghandledefAuthApi;
          await apiFn(params);
          // updatePost
          closeModal();
          createMessage.success('操作成功');
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
